const { Server } = require("socket.io");
const io = new Server({ /* options */ });
const mqtt = require("mqtt");
const client = mqtt.connect("mqtt://47.104.162.101:1883");
const mysql=require('mysql');
const zlIp = "192.168.2.23"
const conn=mysql.createConnection({
  host:'localhost', //mysql服务器地址
  port:3306, //mysql默认端口3306
  user:'root', //mysql登录用户名
  password:'554300', //mysql登录密码
  database:'admin_frame', //访问的数据库名称
  multipleStatements:true, //设置一次请求允许多条sql语句同时执行。默认false
});
conn.connect((err)=>{
  if(err){
      console.log('链接数据库失败');
  }else{
      console.log('链接数据库成功');
  }
});

client.on("connect", function(){
  console.log("MQTT服务器连接成功！");
  client.subscribe("Camera/+/rx")
})

io.on("connection", (socket) => {
  // ...
  console.log(socket.id + "连接成功！");
  socket.on("Camera/tx", (data) => {
    console.log(data);
    client.publish(`Camera/${data.mac}/tx`, JSON.stringify(data), { qos: 0, retain: false })
  })
  
});

client.on("message", function(topic, payload, packer){
  console.log(topic, payload.toString())
  let data = JSON.parse(payload.toString())
  let sql = `REPLACE INTO camera(id, ip, ledstat, url, zlurl ) VALUES('${data.mac}', '${data.ipaddress}', '${data.ledstat}', 'rtsp://${data.ipaddress}/stream3', '${zlIp}/camera/${data.mac}');`
  conn.query(sql,[],(err,results,fields)=>{ //三个参数，sql语句、sql给出的数据、回调函数（err，results[sql语句执行的结果]，fields[涉及到的字段列表]）
    if(err){
        console.log(err);
    }else{
        console.log(results.affectedRows);
        if(results.affectedRows == 2){
          io.emit("ledstat","ledstatchange")
        }
        // (4-3)关闭数据库
        //conn.end()
    }
  });

})

io.listen(3000);